package com.yumingjiang.weichatgtp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.yumingjiang.commontool.util.HttpClientResult;
import com.yumingjiang.commontool.util.HttpClientUtils;
import com.yumingjiang.weichatgtp.service.ChatGPTService;
import com.yumingjiang.weichatgtp.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class ChatGPTServiceImpl implements ChatGPTService {

    @Autowired
    private FileService fileService;
    @NacosValue(value = "${chatgpt.api.url}", autoRefreshed = true)
    private String url;

    @NacosValue(value = "${chatgpt.api.token}", autoRefreshed = true)
    private String token;

    @Override
    public HttpClientResult chat(String question, String fileName) {
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doPost(url, buildHeaders(), buildParams(question), "UTF-8");
            fileService.writeToFile(question, httpClientResult, fileName);
            String newContent = JSONObject.parseObject(httpClientResult.getContent()).getString("result");
            httpClientResult.setContent(newContent);
            return httpClientResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String buildParams(String question) {
        JSONArray messages = new JSONArray();
        messages.add("user:" + question);

        JSONObject requestParams = new JSONObject();
        requestParams.put("system", "你是一个小助手");
        requestParams.put("message", messages);
        requestParams.put("temperature", "0.9");
        return requestParams.toJSONString();
    }

    private HashMap<String, String> buildHeaders() {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("X-APISpace-Token", token);
        headers.put("Authorization-Type", "apikey");
        headers.put("Content-Type", "application/json");
        return headers;
    }

}
